<?php

// 自定义的一个很烂的中间件

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->hasHeader('authorization') === false) {
            return response()->json([
                'status' => 'success',
                'code' => 203,
                'message' => 'Missing "Authorization" header'
            ])->setStatusCode(203);
        }
        $header = $request->header('authorization');
        $token = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));

        if(Cache::has($token)){
            $user = \Cache::get($token);
            // 把 $user传递到控制器，使用 $request->attributes->add();  在控制器的接受方式：$request->get('_user');
            $request->attributes->add(['user' => $user]);
        }else{
            return response()->json([
                'status' => 'success',
                'code' => 401,
                'message' => '请先登录'
            ])->setStatusCode(401);
        }

        return $next($request);
    }
}
